package com.netted.operationassistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.mylhyl.superdialog.SuperDialog;
import com.netted.operationassistant.R;
import com.netted.operationassistant.application.BaseApplication;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.entity.Port;
import com.netted.operationassistant.http.HttpRequest;
import com.netted.operationassistant.utils.FaceVerifyUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GetDeviceActivity extends BaseActivity {

    EditText pwd1,pwd2,pwd3,pwd4,pwd5,pwd6,pwd7;


    EditText[] ets = {pwd2,pwd3,pwd4,pwd5,pwd6,pwd7};
    private Thread thread = null;
    private long time = 0L;
    private volatile boolean run = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_device);
//        FaceSDKManager.getInstance().initialize(this, Constant.licenseID, Constant.licenseFileName);
        FaceSDKManager.getInstance().initialize(this, Constant.licenseID, Constant.licenseFileName);
        pwd1 = (EditText)findViewById(R.id.get_pwd1);
        ets[0] = (EditText)findViewById(R.id.get_pwd2);
        ets[1] = (EditText)findViewById(R.id.get_pwd3);
        ets[2] = (EditText)findViewById(R.id.get_pwd4);
        ets[3] = (EditText)findViewById(R.id.get_pwd5);
        ets[4] = (EditText)findViewById(R.id.get_pwd6);
        ets[5] = (EditText)findViewById(R.id.get_pwd7);


        pwd1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                time = System.currentTimeMillis();
                String[] ss = {null,null,null,null,null,null};

                String s = charSequence.toString();
                if (s != null){
                    for(int index = 0; index < s.length(); index ++){
                        ss[index] = s.substring(index,index+1);
                    }
                }
                for(int index = 0; index < 6; index ++){
                    ets[index].setText(ss[index]);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        showSoftInput(null);
    }
    public void cleanAll(){
        time = System.currentTimeMillis();
        pwd1.setText("");
        ets[0].setText("");
        ets[1].setText("");
        ets[2].setText("");
        ets[3].setText("");
        ets[4].setText("");
        ets[5].setText("");
    }

    public void submit(View view){
        time = System.currentTimeMillis();
        Object catbinetId = sharedPreferencesHelper.getSharedPreference("id",null);
        if (catbinetId == null){
            ToastUtils.showLong("丢失系统数据，请联系管理员！");
        }
        String token = pwd1.getText()+"";
        if (StringUtils.isEmpty(token) || token.length() != 6){
            showDialog("提示","请输入六位有效取机码",null);
            return;
        }
        cleanAll();
        final ProgressDialog loadingDialog = ProgressDialog.show(this,"读取中", "正在验证信息", true, false);
        getByToken(catbinetId+"",token,loadingDialog);
    }


    public void getByToken(String catbinetId,String token,final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("token", token);
        params.put("action", "号码取机");

        String url = Constant.HOST + "/ws/opt/getByToken";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                String studentName = dataJson.getString("studentName");
                                String overTime = dataJson.getString("overTime");
                                String port = dataJson.getString("port");

                                Port p = getPortStatus(port);
                                if (p == null || p.getIsHas().equals("N")){
                                    showDialog("提示", "仓内无平板可取", null);
                                    return;
                                }
                                openPort(port);
                                Thread.sleep(1000);
                                serialValue = "";
                                String text = "你好，"+studentName+"同学，仓门已打开，请取出平板后关闭仓门，使用日期到："+
                                        overTime+"，祝你使用愉快！";
                                Date overDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overTime);
                                if (overDate.getTime()<System.currentTimeMillis()){
                                    text = "你好，"+studentName+"同学，仓门已打开，请取出平板后关闭仓门，使用日期到："+
                                            overTime+"，您的平板已经超出使用时间，请及时充值或归还平板！";
                                }
                                showDialog("提示", text, new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(GetDeviceActivity.this,MenuActivity.class));
                                        GetDeviceActivity.this.finish();
                                    }
                                });
                                playSound(GetDeviceActivity.this,R.raw.s1);
                                return;
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(GetDeviceActivity.this,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }



    public void openCamera(View view){
        Intent intent = new Intent(this,CameraActivity.class);
        intent.putExtra("from","GetDeviceActivity");
        startActivity(intent);


/*
        // 根据需求添加活体动作
        BaseApplication.livenessList.clear();
        BaseApplication.livenessList.add(LivenessTypeEnum.Eye);
        BaseApplication.livenessList.add(LivenessTypeEnum.Mouth);
        BaseApplication.livenessList.add(LivenessTypeEnum.HeadUp);
        BaseApplication.livenessList.add(LivenessTypeEnum.HeadDown);
        BaseApplication.livenessList.add(LivenessTypeEnum.HeadLeft);
        BaseApplication.livenessList.add(LivenessTypeEnum.HeadRight);
        BaseApplication.livenessList.add(LivenessTypeEnum.HeadLeftOrRight);
        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
        config.setLivenessTypeList(BaseApplication.livenessList);
        config.setLivenessRandom(BaseApplication.isLivenessRandom);
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        config.setCheckFaceQuality(true);
        config.setFaceDecodeNumberOfThreads(2);

        FaceSDKManager.getInstance().setFaceConfig(config);
        startActivity(new Intent(this, FaceDetectExpActivity.class));*/
    }



    public void showSoftInput(View view){
        time = System.currentTimeMillis();
        pwd1.setFocusable(true);
        pwd1.setFocusableInTouchMode(true);
        pwd1.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(pwd1,0);
        // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    public void exitActivity(View view){
        //this.finish();
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
        ActivityUtils.finishActivity(GetDeviceActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        time = System.currentTimeMillis();
        thread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (run){
                    if (System.currentTimeMillis() - time > Constant.STATIC_TIME){
                        run = false;
                        Intent intent = new Intent(GetDeviceActivity.this,MenuActivity.class);
                        startActivity(intent);
                        GetDeviceActivity.this.finish();
                    }

                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        thread.start();


        String from = getIntent().getStringExtra("from");
        if ("CameraActivity".equals(from)){
            final ProgressDialog loadingDialog = ProgressDialog.show(GetDeviceActivity.this,"验证提示", "正在验证人脸", true, false);
            loadingDialog.show();
            final String groupId = getIntent().getStringExtra("groupId");

            final String base64 = getIntent().getStringExtra("base64");

            new Thread(new Runnable() {
                @Override
                public void run() {

                    String returnStr = FaceVerifyUtils.search(groupId,base64);
                    JSONObject returnJson = JSONObject.parseObject(returnStr);
                    Integer faceCode = returnJson.getInteger("error_code");
                    if (faceCode == 0){
                        JSONObject resultJson = returnJson.getJSONObject("result");
                        if (resultJson != null){
                            JSONArray userList = resultJson.getJSONArray("user_list");
                            if (userList != null && userList.size() > 0){
                                JSONObject userJson = userList.getJSONObject(0);

                                LogUtils.e("face userJson###################"+userJson);
                                String catbinetId = sharedPreferencesHelper.getSharedPreference(Constant.XML_CATBINET_ID, "") + "";
                                String studentId = userJson.getString("user_id");
                                Float score = userJson.getFloatValue("score");
                                if (score < 85){
                                    showDialog("提示", "人脸识别不匹配", new SuperDialog.OnClickPositiveListener() {
                                        @Override
                                        public void onClick(View v) {
                                            startActivity(new Intent(GetDeviceActivity.this,MenuActivity.class));
                                            GetDeviceActivity.this.finish();
                                        }
                                    });
                                }else{
                                    getByStudentId(catbinetId,studentId,loadingDialog);
                                }


                            }

                        }
                    }else{
                        if (loadingDialog != null && loadingDialog.isShowing()){
                            loadingDialog.dismiss();
                        }
                        String tips = Constant.getFaceCode().get(faceCode);
                        if (StringUtils.isEmpty(tips)){
                            tips = "人脸识别错误";
                        }
                        showDialog("提示", tips, new SuperDialog.OnClickPositiveListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(GetDeviceActivity.this,MenuActivity.class));
                                GetDeviceActivity.this.finish();
                            }
                        });
                    }

                }
            }).start();

        }else{
            playSound(GetDeviceActivity.this,R.raw.s6);
        }
    }


    public void getByStudentId(String catbinetId,String studentId,final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("studentId", studentId);
        params.put("action", "人脸识别取机");

        String url = Constant.HOST + "/ws/opt/getByStudentId";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                String studentName = dataJson.getString("studentName");
                                String overTime = dataJson.getString("overTime");
                                String port = dataJson.getString("port");
                                Port p = getPortStatus(port);
                                if (p == null || p.getIsHas().equals("N")){
                                    showDialog("提示", "仓内无平板可取", null);
                                    return;
                                }

                                openPort(port);
                                Thread.sleep(1000);
                                serialValue = "";
                                String text = "你好，"+studentName+"同学，仓门已打开，请取出平板后关闭仓门，使用日期到："+
                                        overTime+"，祝你使用愉快！";
                                Date overDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overTime);
                                if (overDate.getTime()<System.currentTimeMillis()){
                                    text = "你好，"+studentName+"同学，仓门已打开，请取出平板后关闭仓门，使用日期到："+
                                            overTime+"，平板已经超出使用时间，请及时充值或归还平板！";
                                }
                                showDialog("提示", text, new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(GetDeviceActivity.this,MenuActivity.class));
                                        GetDeviceActivity.this.finish();
                                    }
                                });
                                playSound(GetDeviceActivity.this,R.raw.s1);
                                return;
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(GetDeviceActivity.this,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
        ActivityUtils.finishActivity(GetDeviceActivity.class);
    }


    @Override
    protected void onStop() {
        super.onStop();
        run = false;

        stopSound();
    }
}
